import React, { Component } from 'react'
import MyNavBar from 'components/navbar';
import styles from './index.less'
import router from 'umi/router';
import { Button, Toast } from 'antd-mobile'
import { connect } from 'dva'
import { MyIcon } from 'components/my-icon';
import pdfModel from 'models/pdf'

import sealAndSignatureModel from 'models/sealAndSignature'
import { CERTIFICATION_TYPE,PROCESS_STATUS } from 'utils/Enum';
import { getIsDingTalk } from 'utils/utils';
import commonStyles from 'utils/common.less';

/**
 * @description 用于展示实名认证结果的页面
 * @author 马羽
 * @date 2019-12-26
 * @class RealNameAuthenticationResult
 * @extends {Component}
 */
class RealNameAuthenticationResult extends Component {
  /**
   * 进入页面需要传入status来判断是否认证成功 以及用户信息
   * example /RealNameAuthenticationResult?status=success
   * 两个状态 success error
   * 默认状态是error
   */

   //进入页面需要拿到输入的姓名和身份证
  componentDidMount() {
    Toast.loading('查询结果中', 0)
    let userWsid = localStorage.getItem('userWsid')
    let { dispatch } = this.props
    dispatch({
      type: 'RealNameAuthenticationResultModel/getUserInfo',
      payload: {
        userWsid
      },
      callback: () => {
        Toast.hide()
      }
    })
  }

  render() {
    let { info, result,Certification } = this.props
    let { name, cardId } = info;
    const isDingTalk=getIsDingTalk();
    // if(isDingTalk){
    //   document.addEventListener('backbutton', function(e) {
    //     // 在这里处理你的业务逻辑
    //     router.replace(`/EnterpriseCertificationListBackUps`)
    //     e.preventDefault(); //backbutton事件的默认行为是回退历史记录，如果你想阻止默认的回退行为，那么可以通过preventDefault()实现
    //
    //     // console.log('返回事件触发!')
    //   });
    // }
    // const contentContainer=' '+commonStyles.headerTop;
    const contentContainer=isDingTalk==='true'?'':' '+commonStyles.headerTop;
    let url=this.goBack()
    let message = Certification == CERTIFICATION_TYPE.INTEND_CERTIFICATION?'意愿认证':'认证'
    return (
      <div className={styles.baseLayout}>
        <MyNavBar title={'实名认证'} backUrl={url} gobackStatus={true} />
        <div className={styles.mainWrapper+contentContainer}>
          <div className={styles.headImgWrapper}>
            <div className={styles.circularWrapper}>
              {
                result ==PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR ?
                  <MyIcon type='iconwancheng' className={styles.icon} />
                  :
                  <MyIcon type='iconrenzheng' className={styles.icon} />
              }
            </div>
          </div>
          <div className={styles.title}>
            {
              result == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR ?
                message+'失败'
                :
                '恭喜您，'+message+'成功'
            }
          </div>
          <div className={styles.msg}>
            {
              result == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR?
                '您提交的认证资料未通过审核'
                :
                '您提交的认证资料已通过审核'
            }
          </div>
          <div className={styles.infoWrapper}>
            <div className={styles.info}>
              <div className={styles.name}>
                { name }
              </div>
              <div className={styles.cardId}>
                {
                  cardId ?
                    `身份证号：${cardId}`
                    :
                    null
                }
              </div>
            </div>
          </div>
        </div>
        <div className={styles.btnWrapper}>
          <Button onClick={this.goAuthentication} type="primary" className={styles.btn}>
            {
              result == PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS ?
                '返回'
                :
                '重新填写'
            }
          </Button>
        </div>
      </div>
    )
  }

  goBack=()=>{
    let {  result, Certification } = this.props
    let url=''
    if(Certification === CERTIFICATION_TYPE.INTEND_CERTIFICATION){
      url='/Signature?result='+result
    }else {
      url='/EnterpriseCertificationListBackUps'
    }
    return url
  }

  //跳转实名认证函数
  goAuthentication = () => {
    let {  result, Certification } = this.props
   if(Certification === CERTIFICATION_TYPE.INTEND_CERTIFICATION){
      this.getFormsAndSubmitConfirm('confirm',result)
    }else {
      router.push('/EnterpriseCertificationListBackUps')
    }
  }

  getFormsAndSubmitConfirm=(type,result)=>{//意愿认证成功后请求签署确认并跳转成功页面
    const { dispatch } = this.props;
    const envelopeWsid=localStorage.getItem('envelopeWsid');
    let participantWsid = localStorage.getItem('participantWsid');//参与签署方分配的ID
    let url=''
    dispatch({
      type: 'sealAndSignatureModel/getFormsSearch',
      payload: {
        envelopeWsid: envelopeWsid,
        participantWsid:participantWsid,
        query:{
          fields: null,
          filters: null,
          sorts: null,
          offset: 0,
          limit: 1000,
        },
      },
      callback:(res)=> {
        if (res.length!==0) {//获取当前的表单数据不为空
          const { dispatch } = this.props;
          const envelopeWsid=localStorage.getItem('envelopeWsid');
          let participantWsid = localStorage.getItem('participantWsid');//参与签署方分配的ID
          let signFormsWsid=[];
          res.forEach((item)=>{
            signFormsWsid.push({
              formWsid:item.formWsid,
            });
          });
          dispatch({
            type: 'sealAndSignatureModel/submitConfirm',
            payload: {
              envelopeWsid: envelopeWsid,
              participantWsid:participantWsid,
              formsWsidData:{
                signForms:[...signFormsWsid]
              }
            },
            callback:(res)=>{
              if(res===1){
                if(type==='confirm'){

                  router.push('/SignTheSuccess');
                }else {
                  url ='/SignTheSuccess'
                }
              }else {
                if(type==='confirm'){
                  this.pusrGoBack(result)
                }else {
                  url ='/Signature?result='+result
                }

              }
            }
          })
        }
        else{//表单数据为空
          //提示：还未添加任何表单，不允许签署
          if(type==='confirm'){
            this.pusrGoBack(result)
          }else {
            url ='/Signature?result='+result
          }
          Toast.fail('还未添加任何表单，不允许签署')
        }
      }
    });
    return url
  }
}



const mapStateToProps = state => {
  let { result = 'error', info, Certification } = state.RealNameAuthenticationResultModel
  let { userWsid } = state.pdfModel
  return {
    result, //success error
    info,  //包括用户的信息
    userWsid,
    Certification
  }
}

export default connect(mapStateToProps)(RealNameAuthenticationResult, pdfModel,sealAndSignatureModel)
